<template>
  <div>
    <Pick :data="conditionData.match_rule" :list="list" :max="disable.max" />
  </div>
</template>

<script lang="ts" setup>
import { Condition } from '../type';
import Pick from './Pick';

const props = defineProps<{
  condition: Condition;
}>();

const { condition } = toRefs(props);

const disable = computed(() => {
  const set = new Set();
  let max = 0;
  const gen = list => {
    list.forEach(item => {
      if (item.condition_id) {
        set.add(item.condition_id);
      }
      if ('condition_id' in item) {
        max += 1;
      }
      if (item.children) {
        gen(item.children);
      }
    });
  };
  gen(conditionData.value?.match_rule?.children ?? []);
  return { set, max };
});

const list = computed(() => {
  return conditionData.value.matches.map(item => {
    const condition_id = `${item.website_code}:${item.category_code}:${item.condition_code}卍${item.condition_name}`;
    const name = `${item.website_code}:${item.category_name}:${item.condition_name}`;
    return {
      disabled: disable.value.set.has(condition_id),
      condition_id: condition_id,
      name,
    };
  });
});
const reset = () => {
  conditionData.value.match_rule = {
    type: 'complex',
    logic_type: 'or',
    children: list.value.map(item => ({
      type: 'simple',
      condition_id: item.condition_id,
    })),
    condition_id: '',
  };
};

const conditionData = ref<Condition>(cloneDeep(condition.value) || {});

if (!conditionData.value.match_rule) {
  reset();
}

const validate = () => {
  return new Promise((resolve, reject) => {
    if (disable.value.max < list.value.length) {
      reject('尚有未参与组合的条件，请配置');
    } else {
      condition.value.match_rule = conditionData.value.match_rule;
      resolve('');
    }
  });
};

defineExpose({
  validate,
  reset,
});
</script>
